package com.szjlc.mybatis.sqlinterceptor.config;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 线程池配置
 * @author steve
 * @since 2022-12-04 10:25
 */
@Configuration
// public class ThreadPoolExecutorConfig implements AsyncConfigurer {
public class ThreadPoolExecutorConfig {
    // Java 获取 CPU 核数
    public static final int CPU_CORE_SIZE = Runtime.getRuntime().availableProcessors();


    /* @Bean
    public ThreadPoolExecutor threadPoolExecutor(){

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                cpuCoreSize << 1,
                cpuCoreSize << 2,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(50),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());// 谁调用谁执行
        return executor;
    } */

    /**
     * 配置类实现AsyncConfigurer接口并重写getAsyncExcutor方法，并返回一个ThreadPoolTaskExecutor
     * 这样我们就给Async配置自定义线程池
     */
   /*  @Override
    public Executor getAsyncExecutor() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                cpuCoreSize << 1,
                cpuCoreSize << 2,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(50),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());// 谁调用谁执行
        return executor;
    } */
    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CPU_CORE_SIZE << 1);
        executor.setMaxPoolSize(CPU_CORE_SIZE << 2);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

    @Bean("testExecutor")
    public Executor testExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CPU_CORE_SIZE << 1);
        executor.setMaxPoolSize(CPU_CORE_SIZE << 2);
        // 设置队列容量
        executor.setQueueCapacity(200);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("taskExecutor-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}
